#!/bin/bash

# Redis-rs2 集群启动脚本
# 启动7个集群实例（4主3从架构）

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${CYAN}🚀 Redis-rs2 集群启动脚本${NC}"
echo -e "${CYAN}====================================${NC}"
echo

# 检查项目是否已编译
if [ ! -f "./target/release/cluster_redis_server" ]; then
    echo -e "${YELLOW}⚠️  检测到项目未编译，正在编译...${NC}"
    cargo build --release --bin cluster_redis_server
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ 编译失败，请检查项目代码${NC}"
        exit 1
    fi
fi

# 创建日志目录
mkdir -p logs/cluster

# 清理旧的日志文件
rm -f logs/cluster/*.log

echo -e "${BLUE}📋 集群架构信息：${NC}"
echo -e "   📌 主节点：node1 (7001), node2 (7002), node3 (7003), node4 (7004)"
echo -e "   📌 从节点：node5 (7005->node1), node6 (7006->node2), node7 (7007->node3)"
echo -e "   📌 槽位分配：每个主节点管理 4096 个槽位"
echo -e "   📌 集群端口：17001-17007"
echo

# 定义节点信息
declare -a NODES=("node1" "node2" "node3" "node4" "node5" "node6" "node7")
declare -a PORTS=("7001" "7002" "7003" "7004" "7005" "7006" "7007")
declare -a ROLES=("主节点" "主节点" "主节点" "主节点" "从节点" "从节点" "从节点")

# 启动所有节点
echo -e "${GREEN}🚀 开始启动集群节点...${NC}"
echo

for i in "${!NODES[@]}"; do
    node="${NODES[$i]}"
    port="${PORTS[$i]}"
    role="${ROLES[$i]}"
    
    echo -e "${PURPLE}启动 ${node} (${role}) - 端口 ${port}${NC}"
    
    # 检查端口是否被占用
    if lsof -i :${port} >/dev/null 2>&1; then
        echo -e "${YELLOW}⚠️  端口 ${port} 已被占用，尝试终止占用进程...${NC}"
        lsof -ti :${port} | xargs kill -9 2>/dev/null || true
        sleep 1
    fi
    
    # 启动节点
    nohup ./target/release/cluster_redis_server cluster_configs/${node}.toml \
        > logs/cluster/${node}.log 2>&1 &
    
    # 保存进程ID
    echo $! > logs/cluster/${node}.pid
    
    echo -e "${GREEN}✅ ${node} 已启动 (PID: $!)${NC}"
    
    # 给节点启动时间
    sleep 2
done

echo
echo -e "${GREEN}🎉 所有集群节点启动完成！${NC}"
echo

# 等待集群稳定
echo -e "${YELLOW}⏳ 等待集群初始化和节点发现...${NC}"
sleep 10

# 检查所有节点状态
echo -e "${BLUE}📊 检查节点状态：${NC}"
all_running=true

for i in "${!NODES[@]}"; do
    node="${NODES[$i]}"
    port="${PORTS[$i]}"
    pidfile="logs/cluster/${node}.pid"
    
    if [ -f "$pidfile" ]; then
        pid=$(cat "$pidfile")
        if ps -p $pid > /dev/null 2>&1; then
            # 测试连接
            if nc -z 127.0.0.1 $port 2>/dev/null; then
                echo -e "   ✅ ${node} (端口 ${port}) - ${GREEN}运行中${NC}"
            else
                echo -e "   ⚠️  ${node} (端口 ${port}) - ${YELLOW}正在启动中...${NC}"
            fi
        else
            echo -e "   ❌ ${node} (端口 ${port}) - ${RED}进程已停止${NC}"
            all_running=false
        fi
    else
        echo -e "   ❌ ${node} (端口 ${port}) - ${RED}PID文件不存在${NC}"
        all_running=false
    fi
done

echo
if [ "$all_running" = true ]; then
    echo -e "${GREEN}🎊 集群启动成功！${NC}"
else
    echo -e "${YELLOW}⚠️  部分节点可能启动失败，请检查日志文件${NC}"
fi

echo
echo -e "${CYAN}📝 有用的命令：${NC}"
echo -e "   🔍 查看节点日志: ${BLUE}tail -f logs/cluster/node1.log${NC}"
echo -e "   📊 监控集群状态: ${BLUE}./scripts/cluster_status.sh${NC}"
echo -e "   🛑 停止集群: ${BLUE}./scripts/stop_cluster.sh${NC}"
echo -e "   🧪 运行测试: ${BLUE}./scripts/test_cluster.sh${NC}"
echo

echo -e "${CYAN}🔗 连接信息：${NC}"
echo -e "   📌 主节点连接:"
echo -e "      redis-cli -h 127.0.0.1 -p 7001 -c"
echo -e "      redis-cli -h 127.0.0.1 -p 7002 -c"
echo -e "      redis-cli -h 127.0.0.1 -p 7003 -c"
echo -e "      redis-cli -h 127.0.0.1 -p 7004 -c"
echo

# 显示进程信息
echo -e "${BLUE}📈 进程信息：${NC}"
ps aux | grep cluster_redis_server | grep -v grep | head -7

echo
echo -e "${GREEN}✨ 集群已就绪，可以开始测试！${NC}"